<%@page import="com.infolab.aims.domain.workorder.WorkOrderAdHoc"%>
<%@ include file="/WEB-INF/views/taglib.jsp" %>
<h3>Work Order Form</h3>	
	<form:form id="form" method="post" modelAttribute="workOrder" cssClass="simpleForm workOrderForm" >
		<form:hidden path="workOrderId" id="workOrderId" />
		<form:hidden path="workOrderCode" id="workOrderCode" />
		
		<form:hidden path="accessDepartment.departmentId" />
		 <div class="action">
	  	<c:choose>
	  		<c:when test="${workOrder.workOrderId==null}">
	  			<button type="submit" class="button positive">
	  			Save
	  			</button>
	  			<a href="<c:url value="/workOrder/search" />" class="button">Back</a>
	  		</c:when>
	  		<c:when test="${workOrder.workOrderId!=null}">
	  			<button type="submit"  class="button positive updateBtn">Update</button>
  				<button type="button" class="button positive closeBtn" onclick="closeWorkOrder()">Close Work Order</button>
  				<a href="<c:url value="/workOrder/print/${workOrder.workOrderId}" />" target="_blank" class="button">Print</a>
  				<button  type="button" class="button positive cancelBtn" onclick="cancelWorkOrder()">Cancel Work Order</button>
  				<a href="<c:url value="/workOrder/search" />" class="button">Back</a>
	  		</c:when>
	  	</c:choose>
	 	</div>	
	 	<div class="clear" style="height:1px">&nbsp;</div>
		<jsp:include page="/WEB-INF/views/message.jsp"></jsp:include>
		<div class="tabs clearfix">
        <ul>
        	<li class="active"><img src="${imageUrl}/tab_active.jpg"><span>Taxi Details</span></li>
        	<c:choose>
        		<c:when test="${workOrder.workOrderId!=null}">
        			<li class="active">
            		<span><a href="<c:url value="/workOrder/update/${workOrder.workOrderId}?tab=2" />">Complaint/Repair</a></span>
        		</c:when>
        		<c:otherwise>
        			<li class="inactive">
            		<span>Complaint/Repair</span>
        		</c:otherwise>
        	</c:choose>
            </li>
        </ul>
        </div>
        <div class="content" id="workOrderContent1">
        	<div class="CD_contentStatus clearfix">
            	<span class="left">Work Order Code : <strong>
				${workOrder.workOrderCode}</strong></span>
                <span class="right">Status : <strong>
                <c:choose>
                	<c:when test="${workOrder.workOrderStatus=='CLOSED'}">
                		<span class="red padding4">		
                	</c:when>
                	<c:when test="${workOrder.workOrderStatus=='CANCEL'}">
                		<span class="grey padding4">		
                	</c:when>
                	<c:when test="${workOrder.workOrderStatus=='INQUEUE'}">
                		<span class="blue padding4">		
                	</c:when>
                	<c:when test="${workOrder.workOrderStatus=='INPROCESS'}">
                		<span class="yellow padding4">		
                	</c:when>
                	<c:when test="${workOrder.workOrderStatus=='COMPLETED'}">
                		<span class="green padding4">		
                	</c:when>
                	<c:otherwise>
                		<span class="blue padding4">INQUEUE
                	</c:otherwise>
                </c:choose>
                
                ${workOrder.workOrderStatus}
                </span></strong></span>
        	</div>
	  		<fieldset>
	  		<div class="span-7">
	  		<aims:column cssErrorClass="error" path="vehicleId">
	  		<label>
	  			Taxi No * 
	 		</label>
	 		<c:choose>
	 			<c:when test="${workOrder.workOrderId!=null}">
	 				<form:input path="vehicleId" size="15" disabled="true"/>
	 				<form:hidden path="vehicleId"/>
	 			</c:when>
	 			<c:otherwise>
	 				<form:input path="vehicleId" size="15" />
	 			</c:otherwise>
	 		</c:choose>
	  		<form:errors path="vehicleId"  cssClass="errorSimple" /> 
			</aims:column>
			<aims:column cssErrorClass="error" path="workOrderType" >
	  		<label>
	  			Type  * 
	 		</label>
	  		<form:select path="workOrderType">
	  			<form:option value=""></form:option>
	  			<form:options items="${globalWorkOrderTypeMap}"/>
	  		</form:select>
	  		
	  		 <form:errors path="workOrderType"  cssClass="errorSimple" /> 
			</aims:column>
			<aims:column cssErrorClass="error" path="companyCode" cssClass="span-7">
	  		<label>
	  			Company Code   
	 		</label> 
	 		<form:input path="companyCode" id="companyCode" readonly="true" size="15" />
			</aims:column>
			<aims:column cssErrorClass="error" path="dateBooking" cssClass="span-7">
	  		<label>
	  			Date   
	 		</label> 
	 		<fmt:formatDate value="${workOrder.dateBooking }" pattern="${globalDateFormatJava}"/>
	 		
			</aims:column>
			<aims:column cssErrorClass="error" path="timeCheckIn"  cssClass="span-7">
	  		<label>
	  			Time In   
	 		</label> <fmt:formatDate value="${workOrder.dateBooking }" pattern="HH:mm"/>
			</aims:column>
			<aims:column cssErrorClass="error" path="timeCheckIn" cssClass="span-7">
	  		<label>
	  			Time Start   
	 		</label> <fmt:formatDate value="${workOrder.timeCheckIn}" pattern="HH:mm"/>
			</aims:column>
			<aims:column cssErrorClass="error" path="timeCheckOut"  cssClass="span-7">
	  		<label>
	  			Time Out   
	 		</label> <fmt:formatDate value="${workOrder.timeCheckOut}" pattern="HH:mm"/>
			</aims:column>
			</div>
			<div class="span-8">
	  		<aims:column cssErrorClass="error" path="driverNric" >
	  		<label>
	  			Driver NRIC  * 
	 		</label>
	 		<c:choose>
	 			<c:when test="${workOrder.workOrderStatus=='CLOSED'}">
	 				<form:input path="driverNric" id="driverNric" readonly="true" />
	 			</c:when>
	 			<c:otherwise>	
	 				<form:select path="driverNric" id="driverNric" onchange="populateDriverInfo(this.value)">
	 				</form:select>
	 			</c:otherwise>
	 		</c:choose>
	 		
	  		<form:errors path="driverNric"  cssClass="errorSimple" /> 
			</aims:column>
			<aims:column cssErrorClass="error" path="driverName" >
	  		<label>
	  			Name  * 
	 		</label>
	  		<form:input path="driverName" size="25" id="driverName" /> <form:errors path="driverName"  cssClass="errorSimple" />  
			</aims:column>
			<aims:column cssErrorClass="error" path="driverTelephoneNo" >
	  		<label>
	  			HP  
	 		</label>
	  		<form:input path="driverTelephoneNo" size="20" id="driverTelephoneNo" /> <form:errors path="driverTelephoneNo"  cssClass="errorSimple" /> 
			</aims:column>
			<aims:column cssErrorClass="error" path="driverTelephoneNo" >
	  		<label>
	  			Email  
	 		</label>
	  		<form:input path="driverEmail" size="20" id="driverEmail"  /> <form:errors path="driverEmail"  cssClass="errorSimple" /> 
			</aims:column>
			<aims:column cssErrorClass="error" path="driverType" >
	  		<label>
	  			Driver Type   
	 		</label>
	  		<form:select path="driverType" id="driverType">
	  			<form:option value="R">Relief</form:option>
	  			<form:option value="H">Hirer</form:option>
	  		</form:select> 
	  		
	  		<form:errors path="driverType"  cssClass="errorSimple" /> 
			</aims:column>
			</div>
			<div class="span-7 last">
				
				<p>
				<table class="gridSearch">
				<tbody>
				<tr class="alt"><td width="50%">
					<form:input path="assetModelCode" id="assetModelCode" readonly="true" size="15" /></td>
				<td>
					IVE : <form:input path="meVersion" id="meVersion" readonly="true" size="5" />
				</td></tr>
				</tbody>
				</table>
				
	  			<table class="gridSearch center">
	  				<caption>Number of booking calls</caption>
	  				<thead>
	  				<tr>
	  					<th width=80px>Date</th>
	  					<th>Received Booking</th>
	  					<th>Conformed Booking</th>
	  				</tr>
	  				</thead>
	  				<tbody>
	  				<tr>
	  				<td>2010-01-01</td>
	  				<td align="center">6</td>
	  				<td align="center">1</td>
	  				</tr>
	  				</tbody>
	  			</table>
	  			</p>
			</div>
			</fieldset>
			<fieldset>
	  		<div class="head">
	  		HISTORY
	  		<span>
	  		</span>
	  		</div>
	  		<table class="gridSearch" id="historyTable">
	  		<col width="25%">
 			<col width="15%">
 			<col width="30%">
 			<col width="30%">
			 <thead>	
			 	<tr>
			 		<th>Work Order Code</th>
			 		<th>Date</th>
			 		<th>Technician</th>
			 		<th>Driver Name</th>
			 	</tr>
			 </thead>
			  <tbody>
			 	
			 </tbody>
			 </table>
	  		</fieldset>
			<fieldset>
	  		<div class="head">
	  		AD HOC SERVICE
	  		<span>
	  		</span>
	  		</div>
	  		<table class="gridSearch" id="adHocTable">
	  		<col width="25%">
 			<col width="15%">
 			<col width="50%">
 			<col width="10%">
			 <thead>	
			 	<tr>
			 		<th>Service Type</th>
			 		<th>Appointment Date</th>
			 		<th>Remarks</th>
			 		<th>Completed</th>
			 	</tr>
			 </thead>
			  <tbody>
			 	<c:forEach items="${workOrder.workOrderAdHocs}" var="item" varStatus="status">
			 		<tr>
			 		<td>
			 			
			 			${item.systemCodeValue.systemCodeValueDescription}
			 		</td>
			 		<td>
			 			<fmt:formatDate value="${item.appointmentDate}" pattern="${globalDateTimeFormatJava}"/>
			 			 
			 		</td>
			 		<td>
			 			<textarea rows="2" cols="50" name="adHocRemarks" disabled="disabled">${item.adHocRemarks}</textarea>
			 		</td>
			 		<td>
			 			<input type="hidden" name="workOrderAdHocs[${status.index}].workOrderAdHocId" value="${item.workOrderAdHocId}"> 
			 			<input type="checkbox" name="adHocStatusChk" value="1" onchange="changeAdHocStatus(this)" <c:if test="${item.adHocStatusCompleted}">checked</c:if> />
	  					<input name="workOrderAdHocs[${status.index}].adHocStatus" type="hidden" value="${item.adHocStatus}" />
			 		</td>
			 		</tr>
			 	</c:forEach>
			 </tbody>
			 </table>
	  		</fieldset>
	  		
			<fieldset>
			<div class="span-10">
	  		<div class="head">
	  		IN-VEHICLE PARTS
	  		</div>
	  		<table class="gridSearch"  id="complaintTable">
	  		 <col width="50%">
 			 <col width="50%">
			 <thead>	
			 	<tr>
			 		<th>Model</th>
			 		<th>Serial No</th>
			 	</tr>
			 </thead>
			 
			 <tbody>
			 	<c:forEach items="${workOrder.workOrderParts}" var="item" varStatus="status">
			 		<tr>
			 		<td>
			 			${item.assetModel.assetModelName}
			 		</td>
			 		<td>
			 			${item.oldSerialNo}
			 			<c:choose>
			 				<c:when test="${not empty item.oldSerialNo && not empty item.newSerialNo}">
			 					replace to ${item.newSerialNo}
			 				</c:when>
			 				<c:when test="${empty item.oldSerialNo && not empty item.newSerialNo}">
			 					${item.newSerialNo}
			 				</c:when>
			 			</c:choose>
			 		</td>
			 			
			 		</tr>
			 	</c:forEach>
			 </tbody>
			 </table>
	  		</div>
	  		</fieldset>
	  		</div>
      <div class="action">
	  	<c:choose>
	  		<c:when test="${workOrder.workOrderId==null}">
	  			<button type="submit" class="button positive">
	  			Save
	  			</button>
	  			<a href="<c:url value="/workOrder/search" />" class="button">Back</a>
	  		</c:when>
	  		<c:when test="${workOrder.workOrderId!=null}">
	  			<button type="submit"  class="button positive updateBtn">Update</button>
  				<button type="button" class="button positive closeBtn" onclick="closeWorkOrder()">Close Work Order</button>
  				<a href="<c:url value="/workOrder/print/${workOrder.workOrderId}" />" target="_blank" class="button">Print</a>
  				<button  type="button" class="button positive cancelBtn" onclick="cancelWorkOrder()">Cancel Work Order</button>
  				<a href="<c:url value="/workOrder/search" />" class="button">Back</a>
	  		</c:when>
	  	</c:choose>
	 </div>	
	</form:form>
	
	
	<table id="tmpAdHocTable" style="visibility:hidden">
		<tr class="new">
		<td>
			
	  	</td>
	  	<td>
	  	</td>
	  	<td>
	  		<textarea rows="2" cols="50" name="adHocRemarks"></textarea>
	  	</td>
	  	<td>
	  		<input name="workOrderAdHocs.workOrderAdHocId" type="hidden" />
	  		<input name="adHocStatusChk" type="checkbox" value="1" onchange="changeAdHocStatus(this)" />
	  		<input name="workOrderAdHocs.adHocStatus" type="hidden" value="<%=WorkOrderAdHoc.ADHOCSTATUS_NEW%>" />
	  	</td>
		</tr>
	</table>
	
	<script type="text/javascript">
	
		var faultCode;
		$(document).ready(function() {
			
			disabledEnter($('#form'));
			
			<c:if test="${workOrder.workOrderStatus=='CLOSED' || workOrder.workOrderStatus=='CANCEL' }">
				$('.updateBtn').hide();
				$('.closeBtn').hide();
				$('.cancelBtn').hide();
			</c:if>
			
			var workOrderId = $('#workOrderId');
			var vehicleId = $('#vehicleId');
			var workOrderCode = $('#workOrderCode');
			
			
			if(workOrderId.val()=='' && vehicleId.val()!='')
			{
				$.getJSON("<c:url value="/ajax/adHoc/"></c:url>"+vehicleId.val(), function(data) {
					
					$('#adHocTable tbody').html('');
					for(var i=0;i<data.length;i++)
					{
						var row = $('#tmpAdHocTable tr').clone();
						var rowSize = i;
						
						var workOrderAdHocId = data[i].workOrderAdHocId;
						var serviceType = data[i].systemCodeValue.systemCodeValueDescription;
						var appointmentDate = new Date(data[i].appointmentDate);
						var adHocRemarks = data[i].adHocRemarks;
						
						$('input[name=workOrderAdHocs.workOrderAdHocId]',row).attr('name','workOrderAdHocs['+rowSize+'].workOrderAdHocId').val(workOrderAdHocId);
						$('input[name=workOrderAdHocs.adHocStatus]',row).attr('name','workOrderAdHocs['+rowSize+'].adHocStatus');
						
						$('td:eq(0)',row).text(serviceType);
						$('td:eq(1)',row).text(formatDate(appointmentDate));
						$('td:eq(2) textarea',row).val(adHocRemarks).attr('disabled','disabled');
						
						//$('select[name=vendorAssets.assetModel.assetType]',row).attr('name','vendorAssets['+rowSize+'].assetModel.assetType');			
						
						row.appendTo('#adHocTable tbody');
					}
				});
			}
			if(vehicleId.val()!='')
			{
				
				$.getJSON("<c:url value="/ajax/driver/"></c:url>"+vehicleId.val(), function(dataArr) {
					driverInfo=dataArr;
					var driverNric = $('#driverNric');
					driverNric.find('option').remove();
					if(dataArr.length==0)
						alert('No driver found');
					else
					{
						for(i=0;i<dataArr.length;i++)
						{
							$('<option></option>').val(dataArr[i].driverPK.driverNric).text(dataArr[i].driverPK.driverNric).appendTo(driverNric);	
						}
						var data = dataArr[0];
						
						var currentDriverNric = data.driverPK.driverNric;
						
						<c:choose>
						<c:when test="${not empty workOrder.driverNric}">
							currentDriverNric = '${workOrder.driverNric}';
						</c:when>
						</c:choose>
						populateDriverInfo(currentDriverNric);
					}
				});
				
				
				populateWorkOrderHistory(vehicleId.val(),workOrderCode.val());
				
				
			}
			
			$("#vehicleId").autocomplete("<c:url value="/ajax/vehicle"></c:url>", {
		        dataType: 'json',
		        highlight: false,
		        scroll: true,
		        scrollHeight: 300,
		        autoFill: true,
				mustMatch: true,
		        parse: function(data) {
	                var array = new Array();
	                for(var i=0;i<data.length;i++)
	                {
	                    array[i] = { data: data[i], value: data[i].vehicleId, result: data[i].vehicleId };
	                }
	                return array;
		        },

		        formatItem: function(row) {
		             return row.vehicleId;
		        }
		    });
			
			$("#vehicleId").result(autoCompleteVehicleHandler);
			
		});
		
		
		var driverInfo ;
		function autoCompleteVehicleHandler(event, data, formatted)
		{
			$('#driverNric').val('');
			$('#driverName').val('');
			$('#driverTelephoneNo').val('');
			$('#driverEmail').val('');
			$('#driverType').val('');
			$('#meVersion').val('');
			$('#companyCode').val('');
			
			var driverNric = $('#driverNric');
			driverNric.find('option').remove();
			
			$('#adHocTable tbody').html('');
			
			
			if(data)
			{
				
				if(data.meVersion!=null)
				{
					$('#meVersion').val(data.meVersion);
				}
				
				if(data.assetModelCode!=null)
				{
					$('#assetModelCode').val(data.assetModelCode);
				}
				
				if(data.companyCode!=null)
				{
					$('#companyCode').val(data.companyCode);
				}
				var vehicleId = $('#vehicleId');
				
				populateWorkOrderHistory(vehicleId.val(),'');
				
				$.getJSON("<c:url value="/ajax/driver/"></c:url>"+vehicleId.val(), function(dataArr) {
					driverInfo=dataArr;
					
					if(dataArr.length==0)
						alert('No driver found');
					else
					{
						for(i=0;i<dataArr.length;i++)
						{
							$('<option></option>').val(dataArr[i].driverPK.driverNric).text(dataArr[i].driverPK.driverNric).appendTo(driverNric);	
						}
						var data = dataArr[0];
						
						populateDriverInfo(data.driverPK.driverNric);
					}
					
					
				});
				
				
				$.getJSON("<c:url value="/ajax/adHoc/"></c:url>"+data.vehicleId, function(data) {
					
					for(var i=0;i<data.length;i++)
					{
						
						var row = $('#tmpAdHocTable tr').clone();
						var rowSize = i;
						
						var workOrderAdHocId = data[i].workOrderAdHocId;
						var serviceType = data[i].systemCodeValue.systemCodeValueDescription;
						var appointmentDate = new Date(data[i].appointmentDate);
						var adHocRemarks = data[i].adHocRemarks;
						
						$('input[name=workOrderAdHocs.workOrderAdHocId]',row).attr('name','workOrderAdHocs['+rowSize+'].workOrderAdHocId').val(workOrderAdHocId);
						$('input[name=workOrderAdHocs.adHocStatus]',row).attr('name','workOrderAdHocs['+rowSize+'].adHocStatus');
						
						$('td:eq(0)',row).text(serviceType);
						$('td:eq(1)',row).text(formatDate(appointmentDate));
						$('td:eq(2) textarea',row).val(adHocRemarks).attr('disabled','disabled');
						
						//$('select[name=vendorAssets.assetModel.assetType]',row).attr('name','vendorAssets['+rowSize+'].assetModel.assetType');			
						
						row.appendTo('#adHocTable tbody');
					}
				});
			}
		}
		
		
		function changeAdHocStatus(obj)
		{
			if($(obj).is(':checked'))
				$(obj).next().val('COMPLETED');
			else
				$(obj).next().val('NEW');	
		}
		
		function autoCompleteAssetModelEquipmentHandler(event, data, formatted)
		{
			if (data)
			{
				$(this).parent().find(".assetModelId").val(data.assetModelId);
			}
		}
		
		function closeWorkOrder()
		{
			if(confirm('Do you really want to close the work order ? Please click OK to proceed')){
			$('#form').attr('action','<c:url value="/workOrder/close/${workOrder.workOrderId }"></c:url>');
			$('#form').submit();
			}
		}
		
		function cancelWorkOrder()
		{
			if(confirm('Do you really want to cancel the work order ? Please click OK to proceed')){
			$('#form').attr('action','<c:url value="/workOrder/cancel/${workOrder.workOrderId }"></c:url>');
			$('#form').submit();
			}
		}
		
		function populateDriverInfo(driverNric)
		{
			for(i=0;i<driverInfo.length;i++)
			{
				if(driverInfo[i].driverPK.driverNric==driverNric)
				{
					var data = driverInfo[i];
					
					if(data.driverName!=null)
						$('#driverName').val(data.driverName);
					if(data.driverMobileNo != null)
						$('#driverTelephoneNo').val(data.driverMobileNo);
					if(data.driverEmail!=null)
						$('#driverEmail').val(data.driverEmail);
					if(data.driverType!=null)
						$('#driverType').val(data.driverType);
					
					if(data.driverPK.driverNric!=null) {
						$('select#driverNric option').each(function(index,value){
							
							if(this.value==data.driverPK.driverNric)
							{
								this.selected=true;
								//$('#driverNric').get(0).selectedIndex=index;
								//$(this).attr('selected','selected');
							}
						});
					}
				}
			}
		}
		
		function populateWorkOrderHistory(vehicleId,workOrderCode)
		{
			$.getJSON("<c:url value="/ajax/workOrderHistory"></c:url>", {
				taxiNo : vehicleId,
				workOrderCode : workOrderCode
			},function(data) {
				var historyTable = $('#historyTable tbody');
				historyTable.html('');
				for(var i=0;i<data.length;i++)
				{
					var row = $('<tr></tr>');
					$('<td></td>').html('<a onclick="openPopUpWorkOrderForm('+data[i].workOrderId+')" href="javascript:void(0)">'+data[i].workOrderCode+'<a>').appendTo(row);
					
					var dateBooking = new Date(data[i].dateBooking);
					$('<td></td>').text(formatDate(dateBooking)).appendTo(row);
					
					
					if(data[i].technician!=null)
						$('<td></td>').text(data[i].technician.personName).appendTo(row);
					else
						$('<td></td>').text('').appendTo(row);
					
					if(data[i].driverName!=null)
						$('<td></td>').text(data[i].driverName).appendTo(row);
					else
						$('<td></td>').text('').appendTo(row);
					
					row.appendTo(historyTable);
					
				}
				
				
			});
		}
		
		function openPopUpWorkOrderForm(workOrderId)
		{
			var workOrderUrl = '<c:url value="/workOrder/update/"></c:url>'+workOrderId;
			workOrderUrl+='?tab=2&popUpFlag=Y';
			var newwindow = window.open(workOrderUrl,'_blank',"height=500,width=1100,resizable=yes,scrollbars=yes");
		}
	</script>
	